package org.jeecg.modules.demo.mes.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.demo.mes.entity.MesBaseFactory;
import org.jeecg.modules.demo.mes.entity.MesTechnology;
import org.jeecg.modules.demo.mes.entity.MesTechnologyProcedure;
import org.jeecg.modules.demo.mes.entity.MesWorkOrder;
import org.jeecg.modules.demo.mes.service.IMesBaseFactoryService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.mes.service.IMesTechnologyProcedureService;
import org.jeecg.modules.demo.mes.service.IMesTechnologyService;
import org.jeecg.modules.demo.mes.service.IMesWorkOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 工厂建模
 * @Author: jeecg-boot
 * @Date: 2022-10-26
 * @Version: V1.0
 */
@Api(tags = "工厂建模")
@RestController
@RequestMapping("/mes/mesBaseFactory")
@Slf4j
public class MesBaseFactoryController extends JeecgController<MesBaseFactory, IMesBaseFactoryService> {
    @Autowired
    private IMesBaseFactoryService mesBaseFactoryService;
    @Autowired
    private IMesTechnologyService mesTechnologyService;
    @Autowired
    private IMesTechnologyProcedureService mesTechnologyProcedureService;
    @Autowired
    private IMesWorkOrderService mesWorkOrderService;

    /**
     * 分页列表查询
     *
     * @param mesBaseFactory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工厂建模-分页列表查询")
    @ApiOperation(value = "工厂建模-分页列表查询", notes = "工厂建模-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<IPage<MesBaseFactory>> queryPageList(MesBaseFactory mesBaseFactory,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<MesBaseFactory> queryWrapper = QueryGenerator.initQueryWrapper(mesBaseFactory, req.getParameterMap());
            List<MesBaseFactory> list = mesBaseFactoryService.queryTreeListNoPage(queryWrapper);
            IPage<MesBaseFactory> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = mesBaseFactory.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            mesBaseFactory.setPid(null);
            QueryWrapper<MesBaseFactory> queryWrapper = QueryGenerator.initQueryWrapper(mesBaseFactory, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<MesBaseFactory> page = new Page<MesBaseFactory>(pageNo, pageSize);
            IPage<MesBaseFactory> pageList = mesBaseFactoryService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 【vue3专用】加载节点的子数据
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = mesBaseFactoryService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     *
     * @param async
     * @param pcode
     * @return
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = mesBaseFactoryService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     *
     * @param ls
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = mesBaseFactoryService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    /**
     * 获取子数据
     *
     * @param mesBaseFactory
     * @param req
     * @return
     */
    //@AutoLog(value = "工厂建模-获取子数据")
    @ApiOperation(value = "工厂建模-获取子数据", notes = "工厂建模-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<MesBaseFactory>> queryPageList(MesBaseFactory mesBaseFactory, HttpServletRequest req) {
        QueryWrapper<MesBaseFactory> queryWrapper = QueryGenerator.initQueryWrapper(mesBaseFactory, req.getParameterMap());
        List<MesBaseFactory> list = mesBaseFactoryService.list(queryWrapper);
        IPage<MesBaseFactory> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return
     */
    //@AutoLog(value = "工厂建模-批量获取子数据")
    @ApiOperation(value = "工厂建模-批量获取子数据", notes = "工厂建模-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<MesBaseFactory> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<MesBaseFactory> list = mesBaseFactoryService.list(queryWrapper);
            IPage<MesBaseFactory> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param mesBaseFactory
     * @return
     */
    @AutoLog(value = "工厂建模-添加")
    @ApiOperation(value = "工厂建模-添加", notes = "工厂建模-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesBaseFactory mesBaseFactory) {
        //校验名称
        checkFactoryName(mesBaseFactory);
        mesBaseFactoryService.addMesBaseFactory(mesBaseFactory);
        return Result.OK("添加成功！");
    }

    /**
     * 校验名称唯一性
     */
    private void checkFactoryName(MesBaseFactory mesBaseFactory) {
        final String factoryName = mesBaseFactory.getFactoryName();
        final List<MesBaseFactory> list = mesBaseFactoryService.queryFactoriesByName(factoryName);
        if (list == null || list.size() == 0) {
            return;
        }
        final String exceptionMsg = "工厂名称不能重复";
        final String id = mesBaseFactory.getId();
        if (StringUtils.isBlank(id)) {
            //新增
            throw new JeecgBootException(exceptionMsg);
        }
        //修改（看是不是本身）
        if (list.size() > 1) {
            throw new JeecgBootException(exceptionMsg);
        }
        final MesBaseFactory factory = list.get(0);
        if (!StringUtils.equals(id, factory.getId())) {
            throw new JeecgBootException(exceptionMsg);
        }

    }

    /**
     * 编辑
     *
     * @param mesBaseFactory
     * @return
     */
    @AutoLog(value = "工厂建模-编辑")
    @ApiOperation(value = "工厂建模-编辑", notes = "工厂建模-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MesBaseFactory mesBaseFactory) {
        //校验名称
        checkFactoryName(mesBaseFactory);
        //校验修改后的工厂类别低于父级
        checkFatherFactoryLevel(mesBaseFactory);
        mesBaseFactoryService.updateMesBaseFactory(mesBaseFactory);
        return Result.OK("编辑成功!");
    }

    /**
     * 校验修改后的工厂级别必须低于上级&必须大于下级
     */
    private void checkFatherFactoryLevel(MesBaseFactory mesBaseFactory) {
        final String pid = mesBaseFactory.getPid();
        if (StringUtils.isBlank(pid)) {
            return;
        }
        final String factoryLevel = mesBaseFactory.getFactoryLevel();
        if (StringUtils.isBlank(factoryLevel)) {
            return;
        }
        //判断本级要低于父级的等级
        final MesBaseFactory fatherFactoryFromDB = mesBaseFactoryService.getById(pid);
        if (fatherFactoryFromDB == null) {
            return;
        }
        final String factoryLevelFather = fatherFactoryFromDB.getFactoryLevel();
        if (Integer.parseInt(factoryLevelFather) >= Integer.parseInt(factoryLevel)) {
            throw new JeecgBootException("本级工厂级别必须小于上级");
        }
        //判断本级要高于子集
        final String hasChild = mesBaseFactory.getHasChild();
        final String id = mesBaseFactory.getId();
        if (StringUtils.equals("1", hasChild) && StringUtils.isNotBlank(id)) {
            final List<MesBaseFactory> sons = mesBaseFactoryService.queryFactoriesByPid(id);
            for (MesBaseFactory son : sons) {
                final String sonFactoryLevel = son.getFactoryLevel();
                if (Integer.parseInt(factoryLevel) >= Integer.parseInt(sonFactoryLevel)) {
                    throw new JeecgBootException("本级工厂级别必须大于下级");
                }
            }
        }

    }

    /**
     * 修改工厂状态
     */
    @AutoLog(value = "工厂建模-修改工厂状态")
    @ApiOperation(value = "工厂建模-修改工厂状态", notes = "工厂建模-修改工厂状态")
    @PostMapping("changeFactoryStatue")
    public Result<String> changeFactoryStatue(@RequestBody MesBaseFactory mesBaseFactory, HttpServletRequest request) {
        final String id = mesBaseFactory.getId();
        final String factoryStatus = mesBaseFactory.getFactoryStatus();
        if (StringUtils.isBlank(id)) {
            return Result.ok();
        }
        if (StringUtils.isBlank(factoryStatus)) {
            return Result.ok();
        }
        final MesBaseFactory byId = mesBaseFactoryService.getById(id);
        if (byId == null) {
            return Result.error("数据不存在，请刷新");
        }
        if (StringUtils.equals("2", factoryStatus)) {
            //禁用(检查子集有没有【启用】状态的数据)---本级禁用 子集全部禁用
//				 checkTySonFactoryStatus(byId.getId());
            //禁用（检查有没有被工艺使用了的）
            checkTechnologyUse(byId);
            checkWorkOrderUse(byId);
        } else if (StringUtils.equals("1", factoryStatus)) {
            //启用(检查父级是不是禁用状态)
            final String pid = byId.getPid();
            final MesBaseFactory parentFactory = mesBaseFactoryService.getById(pid);
            if (parentFactory != null) {
                final String parentFactoryStatus = parentFactory.getFactoryStatus();
                if (StringUtils.equals("2", parentFactoryStatus)) {
                    throw new JeecgBootException("上级是禁用状态，请先启用上级再操作");
                }
            }

        }
        mesBaseFactoryService.changeFactoryStatue(mesBaseFactory, JwtUtil.getUserNameByToken(request));
        return Result.ok("操作成功");
    }

    /**
     * 检查该工厂是否有被工单使用
     */
    private void checkWorkOrderUse(MesBaseFactory factory) {
        final String factoryLevel = factory.getFactoryLevel();
        final String id = factory.getId();
        if (Arrays.asList("1", "2", "3").contains(factoryLevel)) {
            final Map<String, Object> cxMap = new HashMap<>();
            if (StringUtils.equals("1", factoryLevel)) {
                cxMap.put("factoryId", id);
            } else if (StringUtils.equals("2", factoryLevel)) {
                cxMap.put("workshopId", id);
            } else {
                cxMap.put("lineId", id);
            }
            final List<MesWorkOrder> mesWorkOrders = mesWorkOrderService.queryTechnologyListSelective(cxMap);
            if (mesWorkOrders != null && mesWorkOrders.size() > 0) {
                throw new JeecgBootException("已被工单绑定，请先修改工单再操作");
            }
        }
    }

    /**
     * 检查该工厂及下级是否有被工艺使用
     */
    private void checkTechnologyUse(MesBaseFactory factory) {
//        根据工厂类型查询工艺表
        final String factoryLevel = factory.getFactoryLevel();
        final String id = factory.getId();
        //工艺表校验
        if (Arrays.asList("1", "2", "3").contains(factoryLevel)) {
            final Map<String, Object> cxMap = new HashMap<>();
            if (StringUtils.equals("1", factoryLevel)) {
                cxMap.put("factoryId", id);
            } else if (StringUtils.equals("2", factoryLevel)) {
                cxMap.put("workshopId", id);
            } else if (StringUtils.equals("3", factoryLevel)) {
                cxMap.put("lineId", id);
            }
            final List<MesTechnology> technologies = mesTechnologyService.queryTechnologyListSelective(cxMap);
            if (technologies != null && technologies.size() > 0) {
                throw new JeecgBootException("已被工艺绑定，请先修改工艺再操作");
            }
        }
        //查看工序表
        if (StringUtils.equals("4", factoryLevel)) {
            final Map<String, Object> cxMap = new HashMap<>();
            cxMap.put("stationId", id);
            final List<MesTechnologyProcedure> procedureList = mesTechnologyProcedureService.queryTechnologyProcedureListSelective(cxMap);
            if (procedureList != null && procedureList.size() != 0) {
                throw new JeecgBootException("已被工序绑定，请先修改工序在操作");
            }
        }

    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工厂建模-通过id删除")
    @ApiOperation(value = "工厂建模-通过id删除", notes = "工厂建模-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        //添加校验
        if (StringUtils.isNotBlank(id)) {
            final MesBaseFactory byId = mesBaseFactoryService.getById(id);
            //校验本身状态
            final String factoryStatus = byId.getFactoryStatus();
            if (StringUtils.equals("1", factoryStatus)) {
                throw new JeecgBootException("有工厂状态是启用中，请先将状态停用再进行操作");
            }
            final String hasChild = byId.getHasChild();
            if (StringUtils.equals("1", hasChild)) {
                //有子项，需要钻取校验
                checkTySonFactoryStatus(byId.getId());
            }
        }
        mesBaseFactoryService.deleteMesBaseFactory(id);
        return Result.OK("删除成功!");
    }

    /**
     * 钻取查看工厂状态是否存在启用的
     */
    private void checkTySonFactoryStatus(String pid) throws JeecgBootException {
        if (StringUtils.isBlank(pid)) {
            return;
        }
        final List<MesBaseFactory> list = mesBaseFactoryService.queryFactoriesByPid(pid);
        if (list == null) {
            return;
        }
        final String msg = "有工厂状态是启用中，请先将状态停用再进行操作";
        for (MesBaseFactory factory : list) {
            //首先校验自身
            final String factoryStatus = factory.getFactoryStatus();
            if (StringUtils.equals("1", factoryStatus)) {
                throw new JeecgBootException(msg);
            }
            //校验子集
            final String hasChild = factory.getHasChild();
            if (StringUtils.equals("1", hasChild)) {
                final String id = factory.getId();
                checkTySonFactoryStatus(id);
            }
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工厂建模-批量删除")
    @ApiOperation(value = "工厂建模-批量删除", notes = "工厂建模-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesBaseFactoryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工厂建模-通过id查询")
    @ApiOperation(value = "工厂建模-通过id查询", notes = "工厂建模-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesBaseFactory> queryById(@RequestParam(name = "id", required = true) String id) {
        MesBaseFactory mesBaseFactory = mesBaseFactoryService.getById(id);
        if (mesBaseFactory == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mesBaseFactory);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesBaseFactory
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesBaseFactory mesBaseFactory) {
        return super.exportXls(request, mesBaseFactory, MesBaseFactory.class, "工厂建模");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_base_factory:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesBaseFactory.class);
    }

}
